package month1;

public class ImplementTrie208_06 {
    public static void main(String[] args) {

    }
}

/**
 * 实现字典树
 */
class Trie {
    Trie[] children;
    boolean isEnd;

    public Trie() {
        children = new Trie[26];
    }

    public void insert(String word) {
        Trie trie = this;
        for (char c: word.toCharArray()) {
            if (trie.children[c - 'a'] == null) {
                trie.children[c - 'a'] = new Trie();
            }
            trie =  trie.children[c - 'a'];
        }
        trie.isEnd = true;
    }

    public boolean search(String word) {
        Trie trie = this;
        for (char c: word.toCharArray()) {
            if (trie.children[c - 'a'] == null) {
                return false;
            }
            trie =  trie.children[c - 'a'];
        }
        return trie.isEnd;
    }

    public boolean startsWith(String prefix) {
        Trie trie = this;
        for (char c: prefix.toCharArray()) {
            if (trie.children[c - 'a'] == null) {
                return false;
            }
            trie =  trie.children[c - 'a'];
        }
        return true;
    }
}
